# flask web 网络编程文件
from flask import Flask, render_template, request,escape
from vsearch import search4letters
from geo import geocode
key = "99b6fd576c6cb06dc071b44d30935237"

app = Flask(__name__)

# 调用日志系统
def log_request(req: 'flask_request', res:str) -> None:
	with open('vsearch.log', 'a') as log:
		print(req.form, req.remote_addr, req.user_agent, res, file=log, sep='|')

# 请求，调用api
@app.route('/search4', methods=['POST'])
def do_search() -> 'html':
	phrase = request.form['phrase']
	letters = request.form['letters']
	address = request.form['address']
	经纬度地理坐标 = geocode(key,address)['geocodes'][0]['location']
	title = 'Here are your results:'
	results = str(search4letters(phrase, letters))
	log_request(request, results)
	return render_template('results.html',
							the_phrase=phrase,
							the_letters=letters,
							the_title=title,
							the_results=results,
							the_address=address,
							the_geocode=经纬度地理坐标)
# 首页
@app.route('/')
@app.route('/entry')
def entry_page():
	return render_template('entry.html',
							the_title='WELCOME TO LJWENNN‘S WEB')

# 在Web中查看日志系统
@app.route('/viewlog')
def view_the_log() -> 'html':
    contents = []
    with open('vsearch.log', 'r') as log:
        for line in log:
            contents.append([])
            for item in line.split('|'):
                contents[-1].append(escape(item))
    titles = ('FORM DATA', 'REMOTE_ADDR', 'USER_AGENT', 'RESYLTS')
    return render_template('viewlog.html',
                           the_title='view log',
                           the_row_titles=titles,
                           the_data=contents,)
app.run(debug=True)